package com.education.platform.api.service.impl;

import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.service.RelUserPaperService;
import com.education.platform.common.enums.RelTypeEnum;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.service.impl.BaseServiceImpl;
import com.education.platform.common.util.StringUtils;
import com.education.platform.dao.RelUserPaperDao;
import com.education.platform.dao.entity.ArticleDO;
import com.education.platform.dao.entity.RelUserPaperDO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* describe: 用户试卷 关联表
* @author : 
* @date: 2020-07-15 08:43:12.033
**/
@Service
public class RelUserPaperServiceImpl extends BaseServiceImpl<RelUserPaperDao,RelUserPaperDO> implements RelUserPaperService {

	private static final Logger LOGGER = LoggerFactory.getLogger(RelUserPaperServiceImpl.class);

    @Autowired
	private RelUserPaperDao relUserPaperDao;

    /**
     * 判断是否已经购买过
     * 试卷   课程   文章
     *
     * @param relType
     * @param paperId
     */
    @Override
    public void checkRel(int relType,int paperId){
        RelUserPaperDO query = new RelUserPaperDO();
        query.setRelType(relType);
        query.setPaperId(paperId);
        query.setUserId(ThreadUser.getUserId());
        query.setDeleted(false);
        List exists =relUserPaperDao.getList(query);
        if(CollectionUtils.isNotEmpty(exists)){
            throw new BusinessException("已购买，请勿重复购买");
        }
    }

    /**
     * 检查
     * @param articleDO
     */
    public void checkPermission( ArticleDO articleDO){
        //免费 不用验证
        if(articleDO.getPrice()==null||articleDO.getPrice()==0){
            return;
        }
        //付费课程，必须登录，验证是否购买
        if (StringUtils.isEmpty(ThreadUser.getUserTokenRedisKey())) {
            throw new BusinessException("付费文章，请先登录！");
        }else{
            RelUserPaperDO r = new RelUserPaperDO();
            r.setRelType(RelTypeEnum.ARTICLE.getValue());
            r.setPaperId(articleDO.getId());
            r.setUserId(ThreadUser.getUserId());
            r.setDeleted(false);
            List list = relUserPaperDao.getList(r);
            if (CollectionUtils.isEmpty(list)){
                throw new BusinessException("请先购买文章");
            }
        }
    }

}
